<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>7-volatile关键字 | Ywrby个人博客网站</title><meta name="keywords" content="Java"><meta name="author" content="Ywrby"><meta name="copyright" content="Ywrby"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="并发编程下，多线程访问变量的不可见性问题指多个线程访问共享变量，会出现一个线程修改变量的值后，其他线程看不到最新值的情况 代码示例：12345678910111213141516171819202122232425262728293031323334353637package VolatileTest;public class VolatileDemo extends Thread&amp;#123;">
<meta property="og:type" content="article">
<meta property="og:title" content="7-volatile关键字">
<meta property="og:url" content="http://ywrby.cn/2021/03/03/7-volatile%E5%85%B3%E9%94%AE%E5%AD%97/index.html">
<meta property="og:site_name" content="Ywrby个人博客网站">
<meta property="og:description" content="并发编程下，多线程访问变量的不可见性问题指多个线程访问共享变量，会出现一个线程修改变量的值后，其他线程看不到最新值的情况 代码示例：12345678910111213141516171819202122232425262728293031323334353637package VolatileTest;public class VolatileDemo extends Thread&amp;#123;">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://ywrby.cn/img/80857290_p0.jpg">
<meta property="article:published_time" content="2021-03-03T05:59:17.000Z">
<meta property="article:modified_time" content="2021-03-03T07:32:04.000Z">
<meta property="article:author" content="Ywrby">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ywrby.cn/img/80857290_p0.jpg"><link rel="shortcut icon" href="/img/title.png"><link rel="canonical" href="http://ywrby.cn/2021/03/03/7-volatile%E5%85%B3%E9%94%AE%E5%AD%97/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '7-volatile关键字',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-03 15:32:04'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><link rel="stylesheet" href="/css/background.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Ywrby个人博客网站" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/ywrby.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/80857290_p0.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Ywrby个人博客网站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">7-volatile关键字</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-03-03T05:59:17.000Z" title="Created 2021-03-03 13:59:17">2021-03-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-03-03T07:32:04.000Z" title="Updated 2021-03-03 15:32:04">2021-03-03</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="7-volatile关键字"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="并发编程下，多线程访问变量的不可见性问题"><a href="#并发编程下，多线程访问变量的不可见性问题" class="headerlink" title="并发编程下，多线程访问变量的不可见性问题"></a>并发编程下，多线程访问变量的不可见性问题</h3><p>指多个线程访问共享变量，会出现一个线程修改变量的值后，其他线程看不到最新值的情况</p>
<h4 id="代码示例："><a href="#代码示例：" class="headerlink" title="代码示例："></a>代码示例：</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> VolatileTest;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileDemo</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> flag=<span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        flag=<span class="keyword">true</span>;</span><br><span class="line">        System.out.println(<span class="string">&quot;flag修改成功！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isFlag</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> flag;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setFlag</span><span class="params">(<span class="keyword">boolean</span> flag)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.flag = flag;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">test</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        VolatileDemo t=<span class="keyword">new</span> VolatileDemo();</span><br><span class="line">        t.start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span>(<span class="keyword">true</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(t.isFlag())&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;判断条件成立，程序正常执行！&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="运行结果："><a href="#运行结果：" class="headerlink" title="运行结果："></a>运行结果：</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">flag修改成功！</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>可以看到程序始终没有成功输出主线程中的判断条件内的内容，说明主线程存储的flag变量的值仍然始终是false,但是子线程中已经成功修改了flag的值为false，这就是并发编程下多线程访问变量的不可见性问题。</p>
<h1 id="变量不可见性的内存语义"><a href="#变量不可见性的内存语义" class="headerlink" title="变量不可见性的内存语义"></a>变量不可见性的内存语义</h1><h2 id="JMM概述"><a href="#JMM概述" class="headerlink" title="JMM概述"></a>JMM概述</h2><p>JMM（Java Memory Model）是Java的一种内存模型，与<strong>Java并发编程有关</strong>的一种模型。</p>
<p>JMM是Java虚拟机规范中所定义的一种内存模型，JMM是<strong>标准化的</strong>，屏蔽掉了底层不同计算机的区别</p>
<p>JMM描述了Java程序中各种变量（<strong>线程共享变量</strong>）的<strong>访问规则</strong>，以及在JVM中将<strong>变量存储</strong>到内存中和从内存中<strong>读取变量</strong>这样的底层细节</p>
<h3 id="JMM规定："><a href="#JMM规定：" class="headerlink" title="JMM规定："></a>JMM规定：</h3><ul>
<li>所有的共享变量都存储于主内存中。（这里所说的变量指的是实例变量和类变量，不包含局部变量，因为局部变量是线程私有的，因此不存在竞争问题）</li>
<li>每一个线程还存在自己的工作内存，线程的工作内存，保留了被线程使用的变量的工作副本</li>
<li>线程对变量的所有的操作（读，取）都必须在工作内存中完成，而不能直接读写主内存中的变量</li>
<li>不同线程之间也不能直接访问对方的工作内存中的变量，线程间变量的值的传递需要通过主内存中转来完成</li>
</ul>
<p><img src="https://ywrbyimg.oss-cn-chengdu.aliyuncs.com/img/%E4%B8%BB%E5%86%85%E5%AD%98%E4%B8%8E%E5%B7%A5%E4%BD%9C%E5%86%85%E5%AD%98.jpg" alt="主内存与工作内存"></p>
<p>上边的例子中，最后循环没有正常执行的原因也就可以解释了，子线程和主线程最开始时都直接从主内存中读取了flag的值并放入工作内存中，此时两个工作内存中的flag值都是false，随后子线程修改了工作内存中的flag的值，并将结果返回到主内存中，即修改了主内存的flag值，但主线程并没有重新读取主内存，也就导致了主线程中的工作内存中flag的值始终为false无法正常进行循环</p>
<h4 id="以上这些也就解释了前面所说的不可见性产生的原因："><a href="#以上这些也就解释了前面所说的不可见性产生的原因：" class="headerlink" title="以上这些也就解释了前面所说的不可见性产生的原因："></a>以上这些也就解释了前面所说的不可见性产生的原因：</h4><p>每个线程都有自己的工作内存，线程都是从主内存拷贝共享变量的副本值，每个线程都是在工作内存中操作共享变量的</p>
<h1 id="变量不可见性的解决"><a href="#变量不可见性的解决" class="headerlink" title="变量不可见性的解决"></a>变量不可见性的解决</h1><h2 id="解决方案一：加锁"><a href="#解决方案一：加锁" class="headerlink" title="解决方案一：加锁"></a>解决方案一：加锁</h2><p>在要使用共享变量前，先将代码上锁（synchronized），就可以解决变量不可见性，要了解这种方式解决问题的原理，就要理解某一个线程在进入synchronized代码块前后，会执行哪些操作。</p>
<p><strong>当某一个线程进入synchronized代码块时，会执行如下操作：</strong></p>
<ol>
<li>线程获得锁</li>
<li><strong>清空工作空间</strong></li>
<li>从主内存拷贝共享变量<strong>最新的值</strong>到工作内存为副本</li>
<li>执行代码</li>
<li>将修改后的副本的值<strong>刷新</strong>回主内存中</li>
<li>线程释放锁</li>
</ol>
<p>了解了上述执行流程就不难发现，只要在使用了共享变量的代码前加锁，就可以在执行当前语句前获取主内存中最新的共享变量的值，自然也就解决了变量不可见性的问题。并且，由于我们只是出于更新变量值的目的加锁，所以上锁的对象是什么就无关紧要了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> VolatileTest;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//解决并发编程下变量不可见性的方案</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 方法一：加锁</span></span><br><span class="line"><span class="comment">* 在访问共享变量的过程中对它上锁（上锁的对象是任意的）</span></span><br><span class="line"><span class="comment">* 方法二：对共享的变量进行volatile关键字修饰</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileDemo2</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> flag=<span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        flag=<span class="keyword">true</span>;</span><br><span class="line">        System.out.println(<span class="string">&quot;flag修改成功！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isFlag</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> flag;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setFlag</span><span class="params">(<span class="keyword">boolean</span> flag)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.flag = flag;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">test2</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        VolatileDemo2 t=<span class="keyword">new</span> VolatileDemo2();</span><br><span class="line">        t.start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="comment">//在访问共享变量前，先对其加锁</span></span><br><span class="line">            <span class="keyword">synchronized</span> (test2.class) &#123;</span><br><span class="line">                <span class="keyword">if</span> (t.isFlag()) &#123;</span><br><span class="line">                    System.out.println(<span class="string">&quot;判断条件成立，程序正常执行！&quot;</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="解决方案二：volatile关键字修饰"><a href="#解决方案二：volatile关键字修饰" class="headerlink" title="解决方案二：volatile关键字修饰"></a>解决方案二：volatile关键字修饰</h2><p>直接在共享变量前加volatile关键字修饰</p>
<h3 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h3><ol>
<li>所有线程从主内存读取到数据放入其对应的工作内存中</li>
<li>某个线程操作有volatile修饰的变量并更改了它的值</li>
<li>当该线程返回这个变量的新值给主内存后，所有其他线程原先的此变量副本失效</li>
<li>当某个线程需要再次操作该变量时，需要从新从主内存中读取最新的变量的值，放入到工作内存中</li>
</ol>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><strong>volatile保证不同线程对共享变量操作的可见性</strong>，也就是说一个线程修改了volatile修饰的变量，当修改写回主内存时，另外一个线程立即看到最新的值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> VolatileTest;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//解决并发编程下变量不可见性的方案</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 方法一：加锁</span></span><br><span class="line"><span class="comment">* 在访问共享变量的过程中对它上锁（上锁的对象是任意的）</span></span><br><span class="line"><span class="comment">* 方法二：对共享的变量进行volatile关键字修饰</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileDemo2</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">boolean</span> flag=<span class="keyword">false</span>;  <span class="comment">//直接对共享的变量进行volatile关键字修饰</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        flag=<span class="keyword">true</span>;</span><br><span class="line">        System.out.println(<span class="string">&quot;flag修改成功！&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isFlag</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> flag;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setFlag</span><span class="params">(<span class="keyword">boolean</span> flag)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.flag = flag;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">test2</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        VolatileDemo2 t=<span class="keyword">new</span> VolatileDemo2();</span><br><span class="line">        t.start();</span><br><span class="line">        <span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (t.isFlag()) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;判断条件成立，程序正常执行！&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="volatile与synchronized比较"><a href="#volatile与synchronized比较" class="headerlink" title="volatile与synchronized比较"></a>volatile与synchronized比较</h2><ul>
<li>volatile只能修饰实例变量或类变量，而synchronized可以修饰方法，或者代码块</li>
<li>volatile保证数据的可见性，但是不保证原子性（多线程进行写操作，不保证线程安全），而synchronized是一种排他（互斥）的机制</li>
</ul>
<h1 id="原子性"><a href="#原子性" class="headerlink" title="原子性"></a>原子性</h1><h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>原子性指的是在一次操作或者多次操作中，要么所有的操作全部得到了执行并且不会受到任何因素的干扰而中断，要么所有的操作都不执行</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> VolatileAtomic;</span><br><span class="line"></span><br><span class="line"><span class="comment">//探究volatile的原子性</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AtomicDemo</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Runnable run=<span class="keyword">new</span> MyRunnable();</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">100</span>;i++)&#123;</span><br><span class="line">            <span class="comment">//启动100条线程</span></span><br><span class="line">            <span class="keyword">new</span> Thread(run).start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyRunnable</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">int</span> count=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//一次任务是一个整体，会进行100次的自增和输出操作</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">100</span>;i++)&#123;</span><br><span class="line">            count++;</span><br><span class="line">            System.out.println(<span class="string">&quot;count====&gt;&quot;</span>+count);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，上述程序执行过程中，最后变量的值在有volatile修饰的情况下和没有volatile修饰的情况下，最终结果都不一定是10000，发生这种情况的原因在于可能同时有多个线程（并行）对变量进行赋值操作，由于volatile的限制它们同时获取到的变量值是一样的，它们最终会返回相同的值回主内存中，这样本来多次的赋值操作就变成了一次，总的赋值操作少了，最终结果自然也无法达到10000，究其根本，<strong>就是volatile并不具备原子性造成的，它只能解决线程的可见性问题</strong></p>
<h2 id="保证原子性的方案"><a href="#保证原子性的方案" class="headerlink" title="保证原子性的方案"></a>保证原子性的方案</h2><h3 id="加锁"><a href="#加锁" class="headerlink" title="加锁"></a>加锁</h3><p>最简单的保证原子性的方案就是对需要同时执行（保证原子性）的代码进行加锁，加锁后这段代码同时只能由持有锁的唯一线程执行，并且加锁的同时也就保证了变量的可见性，不需要再利用volatile修饰变量了</p>
<h3 id="原子类"><a href="#原子类" class="headerlink" title="原子类"></a>原子类</h3><p>Java从JDK1.5开始提供Atomic包，这个包定义了一种<strong>原子操作类</strong>，原子操作类提供了一种简单高效，线程安全的更新一个变量的方式（<strong>因为加锁这种机制的性能比较差</strong>）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AtomicInteger</span><span class="params">()</span></span>;  <span class="comment">//初始化一个默认值为0的原子型Integer</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AtomicInteger</span><span class="params">(<span class="keyword">int</span> initialValue)</span></span>;   <span class="comment">//初始化一个指定值的原子型Integer</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">get</span><span class="params">()</span></span>;   <span class="comment">//获取值</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getAndIncrement</span><span class="params">()</span></span>;  <span class="comment">//以原子方式将当前值加1，注意：这里返回的是自增前的值</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">incrementAndGet</span><span class="params">()</span></span>;  <span class="comment">//以原子方式将当前值加1，注意：这里返回的是自增后的值</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">addAndGet</span><span class="params">(<span class="keyword">int</span> data)</span></span>;  <span class="comment">//以原子方式将输入的数值与实例中的值（AtomicInteger中的value）相加，并返回结果</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getAndSet</span><span class="params">(<span class="keyword">int</span> value)</span></span>;  <span class="comment">//以原子方式设置为newValue的值，并返回旧值</span></span><br></pre></td></tr></table></figure>


<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> VolatileAtomic;</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用原子类保证原子性</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AtomicDemo2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Runnable run=<span class="keyword">new</span> My_Runnable();</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">100</span>;i++)&#123;</span><br><span class="line">            <span class="comment">//启动100条线程</span></span><br><span class="line">            <span class="keyword">new</span> Thread(run).start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">My_Runnable</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line">    <span class="comment">//创建一个Integer更新的原子类,初始值为0</span></span><br><span class="line">    <span class="keyword">private</span> AtomicInteger count=<span class="keyword">new</span> AtomicInteger();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//一次任务是一个整体，会进行100次的自增和输出操作</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">100</span>;i++)&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;count====&gt;&quot;</span>+count.incrementAndGet());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>可以看到，上述程序通过原子类保证了原子性，保证了程序正常执行</strong></p>
<h2 id="原子类CAS机制"><a href="#原子类CAS机制" class="headerlink" title="原子类CAS机制"></a>原子类CAS机制</h2><h3 id="CAS机制"><a href="#CAS机制" class="headerlink" title="CAS机制"></a>CAS机制</h3><h4 id="（Compare-And-Swap）"><a href="#（Compare-And-Swap）" class="headerlink" title="（Compare And Swap）"></a>（Compare And Swap）</h4><p>比较再交换机制，是现代CPU广泛支持的一种对内存中的共享数据进行操作的一种特殊指令。</p>
<p>CAS可以将read-modify-check-write转换为原子操作，这个原子操作直接由处理器保证。</p>
<p>CAS机制当中使用了3个基本操作数：内存地址V，旧的预期值A，要修改的新值B</p>
<p>CAS机制的核心就是比较再交换，它的实现流程是在一个进程中，同时有多个线程获取到同一个共享变量的值，此时由于没有锁的限制它们各自开始对变量进行操作，当某个线程结束对变量的操作并把新值返回到主内存中去之前，它会先行比较此时主内存中共享变量的值和自己刚开始获取到的变量值是否相同，假设相同，就将新值赋给主内存中的共享变量，加入不同，就将当前变量值作废，重新获取最新的变量值并重新开始操作</p>
<h2 id="个人理解：为什么单纯依靠volatile关键字无法解决原子性的问题"><a href="#个人理解：为什么单纯依靠volatile关键字无法解决原子性的问题" class="headerlink" title="个人理解：为什么单纯依靠volatile关键字无法解决原子性的问题"></a>个人理解：为什么单纯依靠volatile关键字无法解决原子性的问题</h2><p>volatile关键字执行的操作是在某个线程将该变量的刷新值返回到主内存后，处理使得其他所有该变量的副本值失效，也就是再次操作这个值必须重新去主内存中获取最新结果。但这样其实并不能彻底实现原子性，会出现一种情况，例如线程A，B获取到相同的共享变量x的值。随后A，B分别对变量x进行操作（虽然不是同时，但他们可以先后操作，此时二者都没有将更新过的变量值返回主内存），随后A线程首先将更新的x值返回主内存，此举使得所有获得x值的线程手中原来的值失效，当然也包括B，但这对B并没有实际影响，B已经完成了对变量x的操作，只剩将变量返回主内存中的过程，所以B线程本质上不会收到影响，而是执行最后一步，将刷新的值返回主内存。这就导致原本应当A，B两个线程对变量进行两次操作，最后实际上只有后刷新的B线程对变量做出了改变。最终导致了原子性的问题产生</p>
<p>但是CAS机制就最终解决了这个问题，它保证了B线程在尝试刷新主内存的值之前会先进行检验，假如主内存中的变量值已经改变，则B线程之前的操作失效，需要重新进行。</p>
<h2 id="CAS与Synchronized：乐观锁，悲观锁"><a href="#CAS与Synchronized：乐观锁，悲观锁" class="headerlink" title="CAS与Synchronized：乐观锁，悲观锁"></a>CAS与Synchronized：乐观锁，悲观锁</h2><h3 id="Synchronized总是从悲观的角度出发，被称为悲观锁。"><a href="#Synchronized总是从悲观的角度出发，被称为悲观锁。" class="headerlink" title="Synchronized总是从悲观的角度出发，被称为悲观锁。"></a>Synchronized总是从悲观的角度出发，被称为悲观锁。</h3><p>总是假设最坏的情况，每次去拿数据的时候都认为别人会修改，所以每次在拿数据的时候都会上锁，防止别人在他使用期间拿到锁（共享资源每次只给一个线程使用，其他线程阻塞，用完后子再把资源转让给其他线程）JDK中的ReentrantLock也是一种悲观锁，整体来说这种方式性能较差</p>
<h3 id="CAS总是从乐观角度出发，被称为乐观锁"><a href="#CAS总是从乐观角度出发，被称为乐观锁" class="headerlink" title="CAS总是从乐观角度出发，被称为乐观锁"></a>CAS总是从乐观角度出发，被称为乐观锁</h3><p>总是假设最好的情况，每次去拿数据的时候都认为别人不会修改，所以不上锁，但是在更新的时候会判断在使用期间别人有没有更新这个数据，综合性能较好</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Ywrby</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://ywrby.cn/2021/03/03/7-volatile%E5%85%B3%E9%94%AE%E5%AD%97/">http://ywrby.cn/2021/03/03/7-volatile%E5%85%B3%E9%94%AE%E5%AD%97/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="/img/80857290_p0.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/03/03/8-%E5%B9%B6%E5%8F%91%E5%8C%85/"><img class="prev-cover" src="/img/68304874_p0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">8-并发包</div></div></a></div><div class="next-post pull-right"><a href="/2021/03/03/6-%E6%AD%BB%E9%94%81/"><img class="next-cover" src="/img/68304874_p0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">6-死锁</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2021/07/27/1-JVM%E5%9F%BA%E7%A1%80/" title="1-JVM基础"><img class="cover" src="/img/illust_3518827_20191113_165540.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-27</div><div class="title">1-JVM基础</div></div></a></div><div><a href="/2021/03/03/1-%E5%BC%82%E5%B8%B8/" title="1-异常"><img class="cover" src="/img/72124553_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">1-异常</div></div></a></div><div><a href="/2021/03/03/10-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8/" title="10-方法引用"><img class="cover" src="/img/72175872_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">10-方法引用</div></div></a></div><div><a href="/2021/03/03/11-Stream%E6%B5%81/" title="11-Stream流"><img class="cover" src="/img/72124553_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">11-Stream流</div></div></a></div><div><a href="/2021/03/03/12-File%E7%B1%BB/" title="12-File类"><img class="cover" src="/img/68304874_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">12-File类</div></div></a></div><div><a href="/2021/03/03/13-%E9%80%92%E5%BD%92/" title="13-递归"><img class="cover" src="/img/83821828_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">13-递归</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/ywrby.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ywrby</div><div class="author-info__description">Students majoring in CS at SWU</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ywrby"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:ywrby0214@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/353923033" target="_blank" title="Bilibili"><i class="fas fa-file-video"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2278431384&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://twitter.com/ywrby1" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="https://www.facebook.com/profile.php?id=100033741068822" target="_blank" title="Facebook"><i class="fab fa-facebook"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">Less is more</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E4%B8%8B%EF%BC%8C%E5%A4%9A%E7%BA%BF%E7%A8%8B%E8%AE%BF%E9%97%AE%E5%8F%98%E9%87%8F%E7%9A%84%E4%B8%8D%E5%8F%AF%E8%A7%81%E6%80%A7%E9%97%AE%E9%A2%98"><span class="toc-number">1.</span> <span class="toc-text">并发编程下，多线程访问变量的不可见性问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%EF%BC%9A"><span class="toc-number">1.1.</span> <span class="toc-text">代码示例：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C%EF%BC%9A"><span class="toc-number">1.2.</span> <span class="toc-text">运行结果：</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E4%B8%8D%E5%8F%AF%E8%A7%81%E6%80%A7%E7%9A%84%E5%86%85%E5%AD%98%E8%AF%AD%E4%B9%89"><span class="toc-number"></span> <span class="toc-text">变量不可见性的内存语义</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JMM%E6%A6%82%E8%BF%B0"><span class="toc-number"></span> <span class="toc-text">JMM概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#JMM%E8%A7%84%E5%AE%9A%EF%BC%9A"><span class="toc-number">1.</span> <span class="toc-text">JMM规定：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%A5%E4%B8%8A%E8%BF%99%E4%BA%9B%E4%B9%9F%E5%B0%B1%E8%A7%A3%E9%87%8A%E4%BA%86%E5%89%8D%E9%9D%A2%E6%89%80%E8%AF%B4%E7%9A%84%E4%B8%8D%E5%8F%AF%E8%A7%81%E6%80%A7%E4%BA%A7%E7%94%9F%E7%9A%84%E5%8E%9F%E5%9B%A0%EF%BC%9A"><span class="toc-number">1.1.</span> <span class="toc-text">以上这些也就解释了前面所说的不可见性产生的原因：</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E4%B8%8D%E5%8F%AF%E8%A7%81%E6%80%A7%E7%9A%84%E8%A7%A3%E5%86%B3"><span class="toc-number"></span> <span class="toc-text">变量不可见性的解决</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%9A%E5%8A%A0%E9%94%81"><span class="toc-number"></span> <span class="toc-text">解决方案一：加锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%9Avolatile%E5%85%B3%E9%94%AE%E5%AD%97%E4%BF%AE%E9%A5%B0"><span class="toc-number"></span> <span class="toc-text">解决方案二：volatile关键字修饰</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">工作原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">2.</span> <span class="toc-text">总结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#volatile%E4%B8%8Esynchronized%E6%AF%94%E8%BE%83"><span class="toc-number"></span> <span class="toc-text">volatile与synchronized比较</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="toc-number"></span> <span class="toc-text">原子性</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number"></span> <span class="toc-text">概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BF%9D%E8%AF%81%E5%8E%9F%E5%AD%90%E6%80%A7%E7%9A%84%E6%96%B9%E6%A1%88"><span class="toc-number"></span> <span class="toc-text">保证原子性的方案</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A0%E9%94%81"><span class="toc-number">1.</span> <span class="toc-text">加锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%9F%E5%AD%90%E7%B1%BB"><span class="toc-number">2.</span> <span class="toc-text">原子类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E5%AD%90%E7%B1%BBCAS%E6%9C%BA%E5%88%B6"><span class="toc-number"></span> <span class="toc-text">原子类CAS机制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#CAS%E6%9C%BA%E5%88%B6"><span class="toc-number">1.</span> <span class="toc-text">CAS机制</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%88Compare-And-Swap%EF%BC%89"><span class="toc-number">1.1.</span> <span class="toc-text">（Compare And Swap）</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AA%E4%BA%BA%E7%90%86%E8%A7%A3%EF%BC%9A%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8D%95%E7%BA%AF%E4%BE%9D%E9%9D%A0volatile%E5%85%B3%E9%94%AE%E5%AD%97%E6%97%A0%E6%B3%95%E8%A7%A3%E5%86%B3%E5%8E%9F%E5%AD%90%E6%80%A7%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number"></span> <span class="toc-text">个人理解：为什么单纯依靠volatile关键字无法解决原子性的问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CAS%E4%B8%8ESynchronized%EF%BC%9A%E4%B9%90%E8%A7%82%E9%94%81%EF%BC%8C%E6%82%B2%E8%A7%82%E9%94%81"><span class="toc-number"></span> <span class="toc-text">CAS与Synchronized：乐观锁，悲观锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Synchronized%E6%80%BB%E6%98%AF%E4%BB%8E%E6%82%B2%E8%A7%82%E7%9A%84%E8%A7%92%E5%BA%A6%E5%87%BA%E5%8F%91%EF%BC%8C%E8%A2%AB%E7%A7%B0%E4%B8%BA%E6%82%B2%E8%A7%82%E9%94%81%E3%80%82"><span class="toc-number">1.</span> <span class="toc-text">Synchronized总是从悲观的角度出发，被称为悲观锁。</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#CAS%E6%80%BB%E6%98%AF%E4%BB%8E%E4%B9%90%E8%A7%82%E8%A7%92%E5%BA%A6%E5%87%BA%E5%8F%91%EF%BC%8C%E8%A2%AB%E7%A7%B0%E4%B8%BA%E4%B9%90%E8%A7%82%E9%94%81"><span class="toc-number">2.</span> <span class="toc-text">CAS总是从乐观角度出发，被称为乐观锁</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）"><img src="/img/67888138_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="22-内存空间扩充（覆盖与交换）"/></a><div class="content"><a class="title" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）">22-内存空间扩充（覆盖与交换）</a><time datetime="2021-12-25T08:15:49.000Z" title="Created 2021-12-25 16:15:49">2021-12-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理"><img src="/img/80857290_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="21-内存与内存管理"/></a><div class="content"><a class="title" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理">21-内存与内存管理</a><time datetime="2021-12-19T09:57:53.000Z" title="Created 2021-12-19 17:57:53">2021-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁"><img src="/img/81934649_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="20-死锁"/></a><div class="content"><a class="title" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁">20-死锁</a><time datetime="2021-12-11T06:20:20.000Z" title="Created 2021-12-11 14:20:20">2021-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程"><img src="/img/72581222_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="19-管程"/></a><div class="content"><a class="title" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程">19-管程</a><time datetime="2021-11-28T08:39:08.000Z" title="Created 2021-11-28 16:39:08">2021-11-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）"><img src="/img/73604608_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="18-信号量相关问题（吸烟者，读者-写者等）"/></a><div class="content"><a class="title" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）">18-信号量相关问题（吸烟者，读者-写者等）</a><time datetime="2021-11-17T12:08:38.000Z" title="Created 2021-11-17 20:08:38">2021-11-17</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/img/80857290_p0.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Ywrby</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">Local search</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.css"><script>(() => {
  document.querySelectorAll('#article-container span.katex-display').forEach(item => {
    btf.wrap(item, 'div', { class: 'katex-wrap'})
  })
})()</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'QkExI1n70lz2qs7pVpmFeKqp-gzGzoHsz',
      appKey: 'WhG61iDj96bflhu6CIpmE9V8',
      placeholder: 'Please leave your footprints',
      avatar: 'mp',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: false,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="5402995011" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-lrctype=0	data-order="random" data-preload="none" data-autoplay="true" muted></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>